<template>
   <div ref="xTermDom"></div>
</template>

<script>
  import { Terminal }  from "xterm"
  import * as fit from 'xterm/lib/addons/fit/fit'
  import * as attach from 'xterm/lib/addons/attach/attach'
  import "xterm/dist/xterm.css"
  Terminal.applyAddon(fit);
  Terminal.applyAddon(attach);
  export default {
    name: 'Console',
    props:{
      cols:{
          type:[Number,String],
          default:"auto"
      },
      rows:{
        type:[Number,String],
        default:"auto"
      },
      path:{
        type:String,
        default:"wss://docker.example.com/containers/mycontainerid/attach/ws"
      }
    },
    methods: {
      runRealTerminal () {
        console.log('webSocket is finished')
      },
      errorRealTerminal () {
        console.log('webSocket is error')
      },
      closeRealTerminal () {
        console.log('webSocket is close')
      }
    },
    mounted(){
      let terminalContainer = this.$refs.xTermDom;
      let { cols,rows } = this;
      let opt = {
        cols, rows
      }
      if(cols === "auto") delete opt.cols;
      if(rows === 'auto') delete opt.rows;

      this.term = new Terminal(opt);
      this.term.open(terminalContainer);
      // open websocket
      this.terminalSocket = new WebSocket(this.path)
      this.terminalSocket.onopen = this.runRealTerminal
      this.terminalSocket.onclose = this.closeRealTerminal
      this.terminalSocket.onerror = this.errorRealTerminal
      this.term.attach(this.terminalSocket);
    }
  }
</script>

<style scoped>

</style>
